<template>
    <n-button type="primary" @click="openModal">新增实训</n-button>

    <n-modal
        v-if="showModal"
        v-model:show="showModal"
        :mask-closable="false"
        title="新增实训"
        :z-index="3"
    >
        <n-card
            style="width: 700px"
            :title="title"
            :bordered="false"
            size="huge"
            role="dialog"
            aria-modal="true"
        >
            <n-form
                ref="formRef"
                :model="formData"
                :rules="rules"
                label-placement="left"
                label-width="auto"
                require-mark-placement="right-hanging"
                size="medium"
                :style="{
                    maxWidth: '640px'
                }"
            >
                <!--实训名称-->
                <n-form-item label="实训名称" path="name">
                    <n-input v-model:value="formData.name" placeholder="请输入实训名称"/>
                </n-form-item>
                <!--实训班级-->
                <n-form-item label="班级" path="training_class">
                    <n-select
                        v-model:value="formData.training_class"
                        placeholder="选择班级"
                        :options="useTeacher.class"
                        children-field="noChildren"
                    />
                </n-form-item>
                <!--实训任务-->
                <n-form-item label="实训任务" path="task">
                    <n-transfer
                        ref="transfer"
                        v-model:value="formData.taskArray"
                        source-filterable
                        :options="useTeacher.getExtractionTask"
                        :render-source-list="renderSourceList"
                    />
                    <!--点击查看实训任务-->
                    <view-task ref="viewTaskRef"/>
                </n-form-item>
                <!--评分权重-->
                <n-form-item label="任务分析评分(%)" path="">
                    <n-slider v-model:value="score.analysis" :step="1" :format-tooltip="formatTooltip"/>
                </n-form-item>
                <n-form-item label="任务执行评分(%)" path="">
                    <n-slider v-model:value="score.perform" :step="1" :format-tooltip="formatTooltip"/>
                </n-form-item>
                <!--两个按钮-->
                <div style="display: flex; justify-content: flex-end">
                    <n-button type="tertiary" @click="clearData">
                        取消
                    </n-button>
                    <n-button @click="handleValidateButtonClick" v-show="taskId===null">
                        保存
                    </n-button>
                    <n-button type="primary" @click="released" v-show="taskId!==null">
                        发布
                    </n-button>
                </div>
            </n-form>
        </n-card>

    </n-modal>

</template>

<script setup>
import {useTeacherStore} from "@/stores/teacher";
import {NTree} from "naive-ui";
import {h} from "vue";
import ViewTask from "@/components/teacher/抽屉/ViewTask.vue";
import workApi from "@/http/workApi";

const props = defineProps(['setKey'])
const useTeacher = useTeacherStore()
// 是否展示模态框
const showModal = ref(false)

function openModal() {
    useTeacher.updateTask(() => {
        showModal.value = true
    })
}


const viewTaskRef = ref(null)
const method = ref("post")
const title = ref("新增实训")

// 表单数据
const formData = ref({
    name: null,
    training_schedule: "未开始",
    training_status: "未发布",
    training_class: null,
    task: [],
    taskArray: null,
    analysis_score: 50,
    perform_score: 50,
})
const taskOptions = ref(useTeacher.task)
// taskOptions.value = useTeacher.getExtractionTask
// 验证规则
const rules = {
    name: {
        required: true,
        trigger: ["blur", "input"],
        message: "实训名称未输入"
    },
    training_class: {
        required: true,
        type: "number",
        trigger: ['blur', 'change'],
        message: '难道没有班级要完成这个实训吗'
    },
    taskArray: {
        required: true,
        type: "array",
        trigger: ['input'],
        message: '不给他们布置任务那也太轻松了吧?'
    },
    score: {
        required: true,
        trigger: ['input'],
        validator(rule, value) {
            if (!value.analysis) {
                return new Error('请填写任务分析评分')
            } else if (!value.perform) {
                return new Error('请填写任务执行评分')
            }
            if (0 > value.analysis > 100) {
                return new Error('必须在0-100之间')
            }
            return true;
        },
    }
}
const formRef = ref(null);
const handleValidateButtonClick = (e) => {
    e.preventDefault()
    formRef.value?.validate((errors) => {
        if (!errors) {
            addTrain()
        } else {
            window.$message.error('好像没有填好, 检查一下吧')
        }
    })
}


// 穿梭框渲染
const renderSourceList = ({onCheck, pattern}) => {
    return h(NTree, {
        style: "margin: 0 4px;",
        labelField: 'label',
        keyField: "value",
        checkable: true,
        selectable: false,
        blockLine: true,
        checkOnClick: false,
        showIrrelevantNodes: false,
        cascade: true,
        data: useTeacher.task,
        pattern,
        checkedKeys: formData.value.taskArray,
        nodeProps: transferClick,
        onUpdateCheckedKeys: (checkedKeys, option) => {
            for (let i = 0; i < checkedKeys.length; i++) {
                if (typeof checkedKeys[i] === 'string') {
                    checkedKeys.splice(i, 1)
                    option.splice(i, 1)
                    --i
                }
            }
            console.log(checkedKeys)
            console.log(option)
            formData.value.task = option
            onCheck(checkedKeys);
            // 点击勾选框时阻止展开查看任务
            isViewTask = false
            setTimeout(() => {
                isViewTask = true
            }, 5)
        }
    })
};
// 能否展开查看任务( 点击勾选框时不展开 )
let isViewTask = true
// 穿梭框数据点击事件--->打开右边抽屉 ---> 展示任务信息
const transferClick = ({option}) => {
    // 如果是任务给节点添加点击事件
    if (option.type === '任务') {
        return {
            onClick() {
                // 能否打开查看任务抽屉
                if (isViewTask) {
                    viewTaskRef.value.openViewTask(option);
                }
            },
        }
    }
}
const formatTooltip = () => {
    return '任务分析评分' + formData.value.analysis_score + '%  任务执行评分' + formData.value.perform_score + "%"
}
// 评分权重
const score = reactive({
    analysis: 50,
    perform: 50,
})
// 监视权重
watch(
    () => [score.analysis, score.perform],
    ([newAnalysis, newPerform], [oldAnalysis, oldPerform]) => {
        if (newAnalysis !== oldAnalysis) {
            formData.value.analysis_score = newAnalysis
            formData.value.perform_score = 100 - newAnalysis
            score.perform = 100 - newAnalysis
        } else if (newPerform !== oldPerform) {
            formData.value.perform_score = newPerform
            formData.value.analysis_score = 100 - newPerform
            score.analysis = 100 - newPerform
        }
    }
)
// 清除数据
const clearData = () => {
    useTeacher.updateTrain()
    props.setKey()
}
const taskId = ref(null)
const addTrain = () => {
    if (method.value === 'post') {
        workApi.post('teacher/training', formData.value).then((r) => {
            taskId.value = r.id
        });
    } else if (method.value === 'put') {
        workApi.put('teacher/training', formData.value).then((r) => {
            taskId.value = r.id
            clearData()
        });
    }

}

function released() {
    workApi.put("teacher/training_publish", {
        id: taskId.value
    }).then(() => {
        clearData()
    })
}

function modify(odlFormData, newTitle, newMethod) {
    showModal.value = true
    console.log(odlFormData)
    score.analysis = odlFormData.analysis_score
    score.perform = odlFormData.perform_score
    taskOptions.value = useTeacher.task
    for (let i of taskOptions.value) {
        i.children = i.children.map(s => {
            for (let j of odlFormData.task) {
                if (j.task_id === s.task_id) {
                    s = j
                }
            }
            return s
        })
    }
    formData.value = {...odlFormData}
    method.value = newMethod
    title.value = newTitle
}

defineExpose({
    modify
})
</script>

<style scoped lang="less">
.n-button {
    //margin: 15px;
}

.n-transfer {
    height: 30vh;
}

.n-input-number {
    width: 100px;
    margin: 0 10px;

    &:nth-child(1) {
        margin-left: 0;
    }
}

.n-drawer-content {
    p {
        display: flex;
        margin-bottom: 15px;
        border-bottom: dashed 1px rgba(142, 139, 142, 0.40);

        b {
            flex: 1;
        }

        span {
            flex: 2;
        }
    }
}

.questions {
    padding: 10px 10%;

    .option {
        margin-left: 5%;
    }
}
</style>